<?php
/**
 * 通过芒果注入最终状态
 */
ini_set('display_errors', 1);
set_time_limit(0);
include_once dirname(dirname(dirname(__FILE__))) . '/mgtv_init.php';
define('ORG_ID', 'jsyx');
include_once dirname(dirname(dirname(__FILE__))) . '/'.ORG_ID.'/init.php';
include_once dirname(dirname(dirname(dirname(__FILE__)))).'/op/op_queue.class.php';
$sp_config = sp_model::get_sp_config(ORG_ID);

//脚本控制配置文件路径
define('CONTROL_STATIC_FILE_NAME', '/data/log/nn_timer/notify_mgtv_result/notify_mgtv_result.txt');
//脚本锁定最长时间
define('CONTROL_STATIC_RUNNING_LOCK_MAX_TIME', '1800');

class notify_mgtv_result extends nn_timer
{

    public function action($params = null)
    {
        $this->msg('开始执行...');
        do_timer_action();
        $this->msg('执行结束...');
    }
}
$notify_mgtv_result = new notify_mgtv_result("notify_mgtv_result", ORG_ID);
$notify_mgtv_result->run();

function do_timer_action()
{
    //读取脚本脚本间隔
    $contents = get_running_flag();
    $time = date('Y-m-d H:i:s',time());
    $last_time = date('Y-m-d H:i:s',strtotime($contents[1]));
    
    if(!check_running_flag())
    {
        exit;
    }
    
    //查询注入成功的主媒资、分集、片源
    $sql = "select nns_op_id from nns_mgtvbk_c2_task where nns_org_id='" . ORG_ID . "' and nns_status=0 and nns_epg_status=99 and nns_modify_time>='{$last_time}' and nns_modify_time<='{$time}'";
    
    $db = nn_get_db(NL_DB_WRITE | NL_DB_READ);
    $result = nl_query_by_db($sql, $db);
    nn_echo_ex_msg("注入成功反馈芒果消息:".$sql.var_export($result,true));
    $op_queue = new op_queue();
    if(is_array($result))
    {
        foreach ($result as $item)
        {
            $re = $op_queue->task_ok($db, $item['nns_op_id']);
            nn_echo_ex_msg("反馈结果:".var_export($re,true));
        }
    }
    set_running_flag(0);
}

/**
 * 写入日志
 * @return true写入成功 false 写入失败
 * @param $msg 信息
 */
function nn_echo_ex_msg($msg)
{
	if (empty($msg))
	{
		return false;
	}	
	//写入日志文件
	$str_cms_dir = dirname(dirname(dirname(dirname(__FILE__)))) . '/';
	$str_log_dir = $str_cms_dir . 'data/log/mgtv/' . ORG_ID . '/notify_mgtv_result/';
	$str_log_file = date('Ymd').'.txt';
	$str_start_time = "[" . date("Y-m-d H:i:s") . "]";
	if (!is_dir($str_log_dir))
	{
		mkdir($str_log_dir, 0777, true);
	}
	file_put_contents($str_log_dir . $str_log_file, $str_start_time . $msg . "\r\n", FILE_APPEND);
	return true;
}
/**
 * 检查是否进程已经完成
 * @return bool
 * TRUE 为已经完成，可以执行脚本
 * FALSE 为未完成，不可执行脚本
 */
function check_running_flag()
{
    nn_echo_ex_msg("检查上一次脚本是否已经停止运行");
    $control_file = dirname(dirname(dirname(dirname(__FILE__)))).CONTROL_STATIC_FILE_NAME;
    //第一次不执行脚本
    if (!file_exists($control_file))
    {
        set_running_flag(0);
        return FALSE;
    }
    
    $control_contents = get_running_flag();

    if ($control_contents[0] == 0)
    {
        nn_echo_ex_msg("上一次脚本已经停止运行");
        set_running_flag(1);
        return TRUE;
    }
    $old_time = strtotime($control_contents[1]);
    $now_time = time();
    if ($control_contents[0] == 1 && ($now_time - $old_time >= CONTROL_STATIC_RUNNING_LOCK_MAX_TIME))
    {
        nn_echo_ex_msg("上一次脚本还在运行，但运行了30分钟，可能是PHP卡死");
        set_running_flag(1);
        return TRUE;
    }
    nn_echo_ex_msg("上一次脚本还在运行");
    return FALSE;
}

/**
 * 写入控制器状态
 * @param $state
 * 0 脚本已经完成
 * 1 脚本暂未完成
 */
function set_running_flag($state)
{
    $control_file = dirname(dirname(dirname(dirname(__FILE__)))).CONTROL_STATIC_FILE_NAME;
    $str_log_dir =  dirname($control_file);
    
    if (!is_dir($str_log_dir))
    {
        mkdir($str_log_dir, 0777, true);
    }
    $datetime = date("YmdHis");
    $controls = $state.','.$datetime;
    file_put_contents($control_file, $controls);
}
/**
 * 取出文件内容
 */
function get_running_flag()
{
	$control_file = dirname(dirname(dirname(dirname(__FILE__)))).CONTROL_STATIC_FILE_NAME;
	$control_content = @file_get_contents($control_file);
	$control_content = trim($control_content);
	return explode(",",$control_content);
}